#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cerrno>
#include <cstring>
#include <string>

#define SIZE 1024
// fork之后子进程能拿到父进程的代码和数据，但是他只是写时拷贝，对方都看不见
std::string GerOtherMessage()
{
    static int cnt = 0;
    std::string messageid = std::to_string(cnt);
    cnt++;

    pid_t self_id = getpid();
    std::string stringpid = std::to_string(self_id);
    std::string message = "messageid: ";
    message += messageid;
    message += " my pid is : ";
    message += stringpid;

    return message;
}
void SubProcessWrite(int wfd)
{
    int pipesize = 0;
    std::string message = "father i am your child ";
    std::cerr<<message<<std::endl;
    char c = 'A';
    while (true)
    {
        std::cerr << "++++++++++++++++++++++++" << std::endl;
        std::string info = message + GerOtherMessage();

        write(wfd, info.c_str(), info.size());
        std::cerr << info << std::endl;
        sleep(1);
    }
    std::cerr << "child quit ... " << std::endl;
}

void FatherProcessRead(int rfd)
{
    char inbuffer[SIZE];
    int cnt = 0;
    while (true)
    {
        std::cout << "-------------------------" << std::endl;
        ssize_t n = read(rfd, inbuffer, sizeof(inbuffer) - 1); // 这里的-1 是留位置给'\0'

        if (n > 0)
        {
            inbuffer[n] = 0;
            std::cout << inbuffer << std::endl;
        }
        if (n == 0)
        {
            std::cout << "child quit , father get return val " << n << "father quit too ..." << std::endl;
            break;
        }
        if (n < 0)
        {
            std::cout << "read error , quit ... " << std::endl;
            break;
        }
    }
    std::cout << "father quit ... " << std::endl;
}
int main()
{
    int pipefd[2];
    int n = pipe(pipefd);
    if (n != 0)
    {
        std::cerr << "pipe fail errno: " << errno << " " << strerror(errno) << std::endl;
        return 1;
    }
    int id = fork();
    if (id == 0)
    {
        std::cerr << "子进程关闭不需要的fd  准备发消息了 " << std::endl;
        // 子进程——write
        // 子进程关闭不需要的fd
        close(pipefd[0]);
        SubProcessWrite(pipefd[1]);
        close(pipefd[1]);
        exit(0);
    }
    std::cout << "父进程关闭不需要的fd 准备读数据了" << std::endl;
    close(pipefd[1]);
    sleep(5);
    FatherProcessRead(pipefd[0]);

    close(pipefd[0]);

    int status;
    pid_t rid = waitpid(id, &status, 0);
    if (rid == -1)
    {
        std::cout << "wait fail quit sig: " << (status & 0x7FF) << std::endl;
    }
    return 0;
}
